package com.lm.curator.example;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class NodeCacheExample {
    public static void main(String[] args) throws Exception {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        client.start();

        // 创建 NodeCache
        NodeCache nodeCache = new NodeCache(client, "/test-node");
        nodeCache.getListenable().addListener(() -> {
            System.out.println("节点数据变更，新的数据为：" + new String(nodeCache.getCurrentData().getData()));
        });

        nodeCache.start();

        // 创建节点并修改数据
        client.create().orSetData().forPath("/test-node", "initial-data".getBytes());
        Thread.sleep(1000);
        client.setData().forPath("/test-node", "updated-data".getBytes());

        Thread.sleep(5000); // 保持运行观察结果
        client.close();
    }
}